package sword.offer.breakthrough;

/**
 * @author 胡宇轩
 * @Email: yuxuan.hu01@bianlifeng.com
 */
public class First {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int divide = solution.divide(Integer.MIN_VALUE, 1);
    }

    static class Solution {
        public int divide(int a, int b) {
            if (a == Integer.MIN_VALUE && b == -1) {
                return Integer.MAX_VALUE;
            }
            int flag = 0;
            if(a > 0){
                flag++;
                a = -a;
            }

            if(b > 0){
                flag++;
                b = -b;
            }
            int res = divideCore(a, b);
            return flag == 1 ? -res : res;
        }

        int divideCore(int a, int b){
            int result = 0;
            while(a <= b){
                int value = b;
                int mul = 1;
                // ！！！！这里为啥要这么加一个判断？防止溢出！！！
                while(value >= Integer.MIN_VALUE >> 1 && a <= value << 1){
                    value <<= 1;
                    mul <<= 1;
                }
                a -= value;
                result += mul;
            }
            return result;
        }
    }
}
